package com.yu.DaoImpl;

import com.yu.Dao.UserDao;
import com.yu.Pojo.User;
import com.yu.utils.Util;

import java.sql.*;

public class UserDaoImpl implements UserDao {
    //执行数据库插入操作
    public int insertUser(User user) throws Exception {
        //实例化 jdbc类 创建连接
        Connection con = Util.reCon();
        // 预编译 执行sql
        String sql = "insert into user values(null,?,?,?,?)";
        PreparedStatement ps = con.prepareStatement(sql);
        //接收用户传来的信息 并赋值给？占位符号 user中获取
        ps.setString(1, user.getUserCode());
        ps.setString(2, user.getUserName());
        ps.setInt(3, user.getGender());
        ps.setString(4, user.getPhone());
        //执行结果
        int i;
        i = ps.executeUpdate();
        //
        Util.closeConAndPs(con, (com.mysql.jdbc.PreparedStatement) ps);

        return i;

    }

    public User selectByName (String username) throws SQLException, ClassNotFoundException {
        Connection con = Util.reCon();
        // 预编译 执行sql
        String sql = "select * from user where username = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        //接收用户传来的信息 并赋值给？占位符号 user中获取
        ps.setString(1,username);
        //执行结果
        ResultSet  rs = ps.executeQuery ();
        User user = null;
        while (rs.next ())
        {
            Integer id = rs.getInt (1);
            String userName = rs.getString(3);

             user = new User ();
            user.setId (id);
            user.setPhone (userName);

        }
        return user;
    }


    public User loginQuery(User user) throws SQLException, ClassNotFoundException {
        Connection con = Util.reCon();
        String sql = "select * from user where userName=? and userCode=?";

        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, user.getUserName());
        ps.setString(2, user.getUserCode());

        ResultSet rs = ps.executeQuery();
        //System.out.println(rs);
        User queryUser = null;
        while (rs.next())
        {
            Integer id = rs.getInt (1);
            String userCode = rs.getString(2);
            String userName = rs.getString(3);
            Integer gender = new Integer(rs.getString(4));
            String phone = rs.getString(5);

            queryUser = new User(id,userCode,userName,gender,phone);
        }

        return queryUser;
    }
}
